#!/usr/bin/env python
"""Script that generates templates from binaries

Arguments: <protocol>  <path_to_file>  <desired template name>  <outputfile>

Outputfile is optional.

Example: ./parse_template.py S1AP utests/resources/S1SetupInitiatingMessage.s1 initiate
"""
from __future__ import with_statement
import sys
import os

def parse(protocol, infile, target_name, outfile=None):
    from ASN1Library import ASN1Library
    with open(infile, 'rb') as input:
        binary = input.read()
    lib = ASN1Library()
    msg = lib.decode_message(protocol, binary)
    result = '''
-module(%s).
-include("../../ebin/%s.hrl").
-export([%s/0]).
%s() -> %s.
''' % (target_name, protocol, target_name, target_name, msg.record)
    if outfile:
        with open(outfile, 'w') as output:
            output.write(result)
    else:
        print result
    lib.teardown_asn1lib()

BASEDIR = os.path.dirname(__file__)

def _set_resources_to_erlang_path():
    erl_path = os.environ.get('ERL_LIBS','')
    erl_path = BASEDIR+os.pathsep+erl_path
    os.environ['ERL_LIBS'] = erl_path
    os.putenv('ERL_LIBS', erl_path)

if __name__ == '__main__':
    if  5 < len(sys.argv) < 4:
        print __doc__
    else:
        _set_resources_to_erlang_path()
        sys.path.insert(0, os.path.join(BASEDIR, 'src'))
        parse(*sys.argv[1:])
